package com.graduate.examapp.view.fragment

import android.app.AlarmManager
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import android.net.ConnectivityManager
import android.net.NetworkInfo
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import android.widget.Toast
import androidx.databinding.DataBindingUtil
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.graduate.examapp.R
import com.graduate.examapp.adapter.HomeExamTaskAdapter
import com.graduate.examapp.broadcast.AlarmBroadcastReciever
import com.graduate.examapp.databinding.FragmentHomeBinding
import com.graduate.examapp.entity.ExamTask
import com.graduate.examapp.entity.UserInfoFactory
import com.graduate.examapp.view.activity.LoginActivity
import com.graduate.examapp.viewmodel.HomeViewModel
import java.time.LocalDateTime
import java.time.ZoneId


class HomeFragment : Fragment() {
    private val homeViewModel: HomeViewModel by lazy {
        val model = ViewModelProvider(this)[HomeViewModel::class.java]
        model
    }
    private var binding: FragmentHomeBinding? = null
    //在创建视图的时候 发起请求 节约资源
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.i("HomeFragment", "create")
        binding = DataBindingUtil.inflate<FragmentHomeBinding>(
            inflater,
            R.layout.fragment_home,
            container,
            false
        )
        //用户基础信息
        init()
        binding?.user = UserInfoFactory.loginData
        return binding?.root
    }

    override fun onResume() {
        super.onResume()
        request()
    }

    private fun init() {
        val recycleView = binding?.root?.findViewById<RecyclerView>(R.id.task_recycle)
        recycleView?.layoutManager =  LinearLayoutManager(this.context, LinearLayoutManager.VERTICAL, false)

        val taskRecycleViewAdapter = HomeExamTaskAdapter()
        recycleView?.adapter = taskRecycleViewAdapter

        homeViewModel.taskLiveData.observe(requireActivity()) {
            it?.let {
                taskRecycleViewAdapter.dataSource = it as MutableList<ExamTask>
                taskRecycleViewAdapter.notifyDataSetChanged()
                Log.d("HomeFragment", taskRecycleViewAdapter.itemCount.toString())
            }
        }

        val logoutBtn = binding?.root?.findViewById<TextView>(R.id.log_out_btn)
        logoutBtn?.setOnClickListener {
            val connectivityManager = this.context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val info: NetworkInfo? = connectivityManager.getActiveNetworkInfo()
            if (info != null && info.isAvailable()) {
                homeViewModel.logout()
            }
            UserInfoFactory.sharedPreference?.let {
                it.edit().clear().apply()
            }
            LoginActivity.start(requireContext())
        }

        homeViewModel.notifyLiveData.observe(requireActivity()) {
            Toast.makeText(this.context, it, Toast.LENGTH_SHORT).show()
        }
    }

    /**
     * 获取页面初始数据
     */
    private fun request() {
        binding?.user?.id?.let {
            val connectivityManager = this.context?.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val info: NetworkInfo? = connectivityManager.getActiveNetworkInfo()
            if (info != null && info.isAvailable()) {
                Log.d("HomeFragment", "发起网络请求")
                homeViewModel.fetchTask(it)
            } else {
                Toast.makeText(this.context, "网络连接不可用", Toast.LENGTH_LONG).show()
            }
        }
    }
}

